import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import {Row, Col, Form, Button, Spin, Table, Modal, Card, Popconfirm} from 'antd';
import {TABLE, FORM_OPTIONS, FORM_ROW_OPTIONS, FIXED_COLUMN_WIDTH} from '../constants';
import TextInput from 'Shared/components/TextInput';
import WrappedSelect from '../common/WrappedSelect';
import styles from './style.css';
import {addSupplierInfo} from './api';
import {injectIntl, language} from './intl';
import {isYorN} from '../Enum';
import CategoryMultiPanel from './CategoryMultiPanel';
import {addSupplierValidator} from './validator';
const FormItem = Form.Item;
const isYorNList = isYorN.toList(language);
class AddSupplierPanel extends PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        data: {},
        showCategoryPanel: false,
        details: [],
        showFile: false,
        errorDetails: []
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onSelectCategory = records => {
        const retailDetails = this.state.details || [];
        records.forEach(r => {
            const index = retailDetails.findIndex(v => v.productCategoryId === r.id);
            if(index === -1)
                retailDetails.push({
                    productCategoryId: r.id,
                    productCategoryCode: r.code,
                    productCategoryName: r.name
                });
        });
        this.setState({
            details: [...retailDetails],
            hasOperat: true,
            showCategoryPanel: false
        });
    }
    onClickAddBtn = () => {
        this.setState({showCategoryPanel: true});
    }
    onCloseCategoryPanel = () => {
        this.setState({showCategoryPanel: false});
    }
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onSubmit = () => {
        const {data, details} = this.state;
        const isValid = addSupplierValidator(data);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({loading: true});
        const addCondition = {
            brandId: this.props.brandId,
            code: data.code,
            name: data.name,
            isNeedPicture: data.isNeedPicture ? data.isNeedPicture === 1 : undefined,
            remark: data.remark,
            details: details.map(v => ({
                productCategoryId: v.productCategoryId
            })),
        };
        addSupplierInfo(addCondition).then(res => {
            if(res.ok)
                this.props.onSelect({
                    id: res.data.id,
                    code: data.code,
                    name: data.name,
                });
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onDeleteAll = () => {
        this.setState({
            details: [],
            hasOperat: true
        });
    }
    onDeleteDetail = e => {
        const productCategoryId = e.target.dataset.id;
        const tmp = this.state.details.filter(d => d.productCategoryId !== productCategoryId);
        this.setState({
            details: [...tmp],
            hasOperat: true
        });
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, details, loading} = this.state;
        const validateCode = !data.code && this.state.validate ? 'error' : null;
        const validateName = !data.name && this.state.validate ? 'error' : null;
        const validateRemark = data.remark && data.remark.length > 100 && this.state.validate ? 'error' : null;
        const colums = [{
            title: formatMessage({
                id: 'addSupplierPanel.column.productCategoryCode',
                defaultMessage: '车型编号'
            }),
            dataIndex: 'productCategoryCode',
        }, {
            title: formatMessage({
                id: 'addSupplierPanel.column.productCategoryName',
                defaultMessage: '车型姓名'
            }),
            dataIndex: 'productCategoryName',
        }, {
            title: details && details.length > 0
                ? (
                    <Popconfirm placement="topRight" title={formatMessage({
                        id: 'addSupplierPanel.column.allDelete',
                        defaultMessage: '是否确认全部删除？'
                    })} onConfirm={this.onDeleteAll} >
                        <a>{formatMessage({
                            id: 'addSupplierPanel.column.empty',
                            defaultMessage: '清空'
                        })}</a>
                    </Popconfirm>
                )
                : <a>{formatMessage({
                    id: 'addSupplierPanel.column.empty',
                    defaultMessage: '清空'
                })}</a>,
            dataIndex: 'productCategoryId',
            fixed: 'right',
            width: FIXED_COLUMN_WIDTH,
            render: text => <a data-id={text} onClick={this.onDeleteDetail}>{formatMessage({
                id: 'addSupplierPanel.column.delete',
                defaultMessage: '删除'
            })}</a>
        }];
        return (
            <Modal
                title={formatMessage({
                    id: 'addSupplierPanel.show.addSupplier',
                    defaultMessage: '新增供应商'
                })}
                width="60%"
                maskClosable={false}
                footer={null}
                destroyOnClose={true}
                wrapClassName={styles.dataSelectModal}
                visible={true}
                onCancel={this.props.onCancel}>
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'addSupplierPanel.column.common',
                        defaultMessage: '基本信息'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addSupplierPanel.operation.code',
                                        defaultMessage: '供应商编号'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateCode}
                                    required>
                                        {this.props.id ? data.code : <TextInput
                                            name="code"
                                            value={data.code}
                                            onBlur={this.onChange} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addSupplierPanel.operation.name',
                                        defaultMessage: '供应商名称'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateName}
                                    required>
                                        <TextInput
                                            name="name"
                                            value={data.name}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        validateStatus={this.state.isValidate && !this.state.isNeedPicture ? 'error' : null}
                                        required
                                        label={this.props.intl.formatMessage({
                                            id: 'addSupplierPanel.add.form.isNeedPicture',
                                            defaultMessage: '是否需要图片'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <WrappedSelect
                                            allowClear
                                            name="isNeedPicture"
                                            value={data.isNeedPicture}
                                            options={isYorNList}
                                            onChange={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <FormItem {...FORM_ROW_OPTIONS.item} label={formatMessage({
                                    id: 'addSupplierPanel.operation.remark',
                                    defaultMessage: '备注'
                                })} validateStatus={validateRemark}>
                                    <TextInput
                                        type="textarea"
                                        name="remark"
                                        value={data.remark}
                                        onBlur={this.onChange} />
                                </FormItem>
                            </Row>
                        </Form>
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'addSupplierPanel.operation.detail',
                            defaultMessage: '不供车型清单'
                        })}
                        extra={<div>
                            <Button
                                size="small"
                                onClick={this.onClickAddBtn}>
                                {formatMessage({
                                    id: 'addSupplierPanel.operation.newDetail',
                                    defaultMessage: '新增车型'
                                })}
                            </Button>
                        </div>}>
                        <Table
                            className="white-space-nowrap"
                            columns={colums}
                            rowKey="productCategoryId"
                            pagination={false}
                            dataSource={details}
                            {...TABLE} />
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            loading={loading}>
                            {formatMessage({
                                id: 'addSupplierPanel.operation.onSubmit',
                                defaultMessage: '保存'
                            })}
                        </Button>
                    </Card>
                    {
                        this.state.showCategoryPanel &&
                        <CategoryMultiPanel
                            currentSelectRowkeys={details}
                            selectKey={data.productCategoryId}
                            onCancel={this.onCloseCategoryPanel}
                            onSelect={this.onSelectCategory} />
                    }
                </Spin>
            </Modal >
        );
    }
}

AddSupplierPanel.propTypes = {
    brandId: PropTypes.string,
    intl: PropTypes.object,
    onCancel: PropTypes.func,
    onSelect: PropTypes.func,
};

export default injectIntl(AddSupplierPanel);
